package com.haier.tv.mic.detect;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.haier.tv.mic.detect.manager.HaierMicManager;
import com.haier.tv.mic.detect.util.LogUtil;
import com.haier.tv.mic.detect.util.Utils;

import java.io.File;

public class MicDetectActivity extends Activity {

    public static final String TAG = "MicDetectActivity";
    public Context mContext = null;
    public TextView channel1TextView = null;
    public TextView channel2TextView = null;
    public TextView channel3TextView = null;
    public TextView channel4TextView = null;
    public TextView channelStateTextView = null;
    public LinearLayout mLinearLayoutChannel1;
    public LinearLayout mLinearLayoutChannel2;
    public LinearLayout mLinearLayoutChannel3;
    public LinearLayout mLinearLayoutChannel4;
    private static final int DETECT_MEDIA_NUM = 0;
    private static final int SUCCESS_MEDIA_NUM = 1;
    private static final int FAIL_MEDIA_NUM = 2;
    private int playMediaNum = DETECT_MEDIA_NUM;
    private String chOne;
    private String chTwo ;
    private String chThree ;
    private String chFour ;
    private int channelNum;
    public MediaPlayer mMediaPlayer ;

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler(){

        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 0x00:
                    channelStateTextView.setVisibility(View.VISIBLE);
                    channelStateTextView.setTextColor(getColor(R.color.white));
                    channelStateTextView.setText("正在录音，请稍后");
                    break;
                case 0x01:
                    channelStateTextView.setVisibility(View.VISIBLE);
                    channelStateTextView.setTextColor(getColor(R.color.green));
                    channel1TextView.setTextColor(getColor(R.color.green));
                    channel2TextView.setTextColor(getColor(R.color.green));
                    channel3TextView.setTextColor(getColor(R.color.green));
                    channel4TextView.setTextColor(getColor(R.color.green));
                    channelStateTextView.setText("麦克风正常");
                    Utils.setProperty("mic_test_result","true");
                    mHandler.sendEmptyMessage(0x03);

                    break;
                case 0x02:
                    channel1TextView.setTextColor(getColor(R.color.red));
                    channel2TextView.setTextColor(getColor(R.color.red));
                    channel3TextView.setTextColor(getColor(R.color.red));
                    channel4TextView.setTextColor(getColor(R.color.red));
                    channelStateTextView.setVisibility(View.VISIBLE);
                    channelStateTextView.setTextColor(getColor(R.color.red));
                    channelStateTextView.setText("麦克风异常");
                    mHandler.sendEmptyMessage(0x03);
                    break;
                case 0x03:
                {
                    if (channelNum == 4) {

                        channel1TextView.setVisibility(View.VISIBLE);
                        channel2TextView.setVisibility(View.VISIBLE);
                        channel3TextView.setVisibility(View.VISIBLE);
                        channel4TextView.setVisibility(View.VISIBLE);

                        chOne = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch0_db", "error");
                        chTwo = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch1_db", "error");
                        chThree = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch2_db", "error");
                        chFour = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch3_db", "error");

                        if (chOne.equalsIgnoreCase("-inf")) {
                            Settings.System.putFloat(mContext.getContentResolver(),"mic_ch1_db", (float) Double.NEGATIVE_INFINITY);
                        } else {
                            Settings.System.putFloat(mContext.getContentResolver(),"mic_ch1_db", (float) Double.parseDouble(chOne));
                        }

                        if (chTwo.equalsIgnoreCase("-inf")) {
                            Settings.System.putFloat(mContext.getContentResolver(), "mic_ch2_db", (float) Double.NEGATIVE_INFINITY);
                        } else {
                            Settings.System.putFloat(mContext.getContentResolver(),"mic_ch2_db", (float) Double.parseDouble(chTwo));
                        }

                        if (chThree.equalsIgnoreCase("-inf")) {
                            Settings.System.putFloat(mContext.getContentResolver(),"mic_ch3_db", (float) Double.NEGATIVE_INFINITY);
                        }else {
                            Settings.System.putFloat(mContext.getContentResolver(),"mic_ch3_db", (float) Double.parseDouble(chThree));
                        }
                        if (chFour.equalsIgnoreCase("-inf")) {
                            Settings.System.putFloat(mContext.getContentResolver(),"mic_ch4_db", (float) Double.NEGATIVE_INFINITY);
                        }else {
                            Settings.System.putFloat(mContext.getContentResolver(),"mic_ch4_db", (float) Double.parseDouble(chFour));
                        }

                        channel1TextView.setText(chOne);
                        channel2TextView.setText(chTwo);
                        channel3TextView.setText(chThree);
                        channel4TextView.setText(chFour);
                    }else if (channelNum == 2){

                        channel1TextView.setVisibility(View.VISIBLE);
                        channel2TextView.setVisibility(View.VISIBLE);

                        channel3TextView.setVisibility(View.GONE);
                        channel4TextView.setVisibility(View.GONE);
                        chOne = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch0_db", "error");
                        chTwo = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch2_db", "error");
                        channel1TextView.setText(chOne);
                        channel2TextView.setText(chTwo);
                    }
                    break;
                }
                case 0x04:
                {
                    finish();
                    break;
                }
                default:break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_mic_detect);
        Utils.setProperty("mic_test_result","false");
        channelNum = HaierMicManager.getHaierMicManager().getMicNum();
        LogUtil.d(TAG,"channelNum " + channelNum);
        mMediaPlayer = new MediaPlayer();
        initViews();
        initMediaPlayer();
        initPlayDetectAudio();
    }

    private void initPlayDetectAudio() {

        mMediaPlayer.reset();
        try {
            AssetFileDescriptor afd = getAssets().openFd("detect.wav");
            mMediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); // 设置媒体数据的文件路径
            mMediaPlayer.prepare(); // 媒体播放器准备就绪
            playMediaNum = DETECT_MEDIA_NUM;

        } catch (Exception e) {
            LogUtil.e(TAG,"playRecord error");
        }
    }

    private void initPlaySuccessAudio(){

        mMediaPlayer.reset();
        try {
            AssetFileDescriptor afd = getAssets().openFd("success.wav");
            mMediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); // 设置媒体数据的文件路径
            mMediaPlayer.prepare(); // 媒体播放器准备就绪
            playMediaNum = SUCCESS_MEDIA_NUM;

        } catch (Exception e) {
            LogUtil.e(TAG,"playRecord error");
        }
    }

    private void initPlayFailAudio(){

        mMediaPlayer.reset();
        try {
            AssetFileDescriptor afd = getAssets().openFd("fail.wav");
            mMediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); // 设置媒体数据的文件路径
            mMediaPlayer.prepare(); // 媒体播放器准备就绪
            playMediaNum = FAIL_MEDIA_NUM;

        } catch (Exception e) {
            LogUtil.e(TAG,"playRecord error");
        }
    }

    private void initMediaPlayer() {
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {

                LogUtil.d(TAG,"onPrepared");
                if (!mMediaPlayer.isPlaying())
                    mMediaPlayer.start();
                if (playMediaNum == DETECT_MEDIA_NUM){

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            HrTvApi.getInstance().beforeMicDetectInit();
                            if (HaierMicManager.getHaierMicManager().micInit(6,16000)) {
                                LogUtil.d(TAG, "HaierMicManager micInit Success");
                                mHandler.sendEmptyMessage(0x00);
                            }
                        }
                    }).start();
                }
            }
        });

        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {

                if (playMediaNum == DETECT_MEDIA_NUM){

                    if (HaierMicManager.getHaierMicManager().micDeInit()){
                        LogUtil.d(TAG,"HaierMicManager micDeInit Success");
                    }
                    boolean isOk = HaierMicManager.getHaierMicManager().checkMicOk();
                    if (isOk){
                        mHandler.sendEmptyMessage(0x01);
                        initPlaySuccessAudio();
                    }else{
                        mHandler.sendEmptyMessage(0x02);
                        initPlayFailAudio();
                    }
                }else if (playMediaNum == SUCCESS_MEDIA_NUM || playMediaNum == FAIL_MEDIA_NUM){
                    mHandler.sendEmptyMessageDelayed(0x04,5000);
                }
            }
        });
    }

    private void initViews() {
        mLinearLayoutChannel1 = (LinearLayout)findViewById(R.id.channel1_layout) ;
        mLinearLayoutChannel2 = (LinearLayout)findViewById(R.id.channel2_layout) ;
        mLinearLayoutChannel3 = (LinearLayout)findViewById(R.id.channel3_layout) ;
        mLinearLayoutChannel4 = (LinearLayout)findViewById(R.id.channel4_layout) ;

        channel1TextView = (TextView) findViewById(R.id.mic_channel1_state_text_view);
        channel2TextView = (TextView) findViewById(R.id.mic_channel2_state_text_view);
        channel3TextView = (TextView) findViewById(R.id.mic_channel3_state_text_view);
        channel4TextView = (TextView) findViewById(R.id.mic_channel4_state_text_view);
        channel1TextView.setVisibility(View.INVISIBLE);
        channel2TextView.setVisibility(View.INVISIBLE);
        channel3TextView.setVisibility(View.INVISIBLE);
        channel4TextView.setVisibility(View.INVISIBLE);

        channelStateTextView = (TextView) findViewById(R.id.mic_state_text_view);
        channelStateTextView.setVisibility(View.INVISIBLE);

        if (channelNum == 4) {
            mLinearLayoutChannel1.setVisibility(View.VISIBLE);
            mLinearLayoutChannel2.setVisibility(View.VISIBLE);
            mLinearLayoutChannel3.setVisibility(View.VISIBLE);
            mLinearLayoutChannel4.setVisibility(View.VISIBLE);
        }else if (channelNum == 2){
            mLinearLayoutChannel1.setVisibility(View.VISIBLE);
            mLinearLayoutChannel2.setVisibility(View.VISIBLE);
            mLinearLayoutChannel3.setVisibility(View.GONE);
            mLinearLayoutChannel4.setVisibility(View.GONE);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK)
            finish();
        return super.onKeyDown(keyCode, event);
    }
}